package com.jcnet.bizaia.service;

import java.io.IOException;
import java.io.Serializable;
import java.nio.channels.AsynchronousCloseException;
import java.text.BreakIterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.R.integer;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.widget.Toast;

import com.jcnet.bizaia.App;
import com.jcnet.bizaia.bean.MusicStateBean;
import com.jcnet.bizaia.bean.VoiceDetailBean;
import com.jcnet.bizaia.fragment.MusicMediaControllerFragment;
import com.jcnet.bizaia.xstream.ACache;

public class JCMusicPlayerService extends Service {

	private final IBinder mBinder = new LocalBinder();

	private MediaPlayer mediaPlayer;

	private  int playNum = 0;   

	List<VoiceDetailBean> musicBeans;

	private OnPreparedListener onPreparedListener;

	private Timer timer ;    //监听seekbar的线程

	private int  bufferSize ;   //缓冲区百分比\

	public static int state;

	public static VoiceDetailBean voiceDetailBean;

	public static final String MUSIC_LIST_CATCHE = "MUSIC_LIST_CATCHE";


	private final int play = 111;
	private final int pause = 222;
	private final int next = 333;
	private final  int previous = 444;
	private final int setList = 555;
	private BroadcastReceiver broadcastReceiver ;
	
	public static final String MUSIC_PLAY = "MUSIC_PLAY";
	public static final String MUSIC_PAUSE = "MUSIC_PAUSE";
	public static final String MUSIC_NEXT= "MUSIC_NEXT";
	public static final String MUSIC_PREVIOUS = "MUSIC_PREVIOUS";
	public static final String MUSIC_SET_LIST  = "MUSIC_SET_LIST";
	
	
	
	public static final String LIST_DATA = "LIST_DATA";
	
	public static final String  LIST_POSTION  ="String";


	private Handler handler ;

	public static enum  PLAYER_STATE{
		PLAY,
		PAUSE
	}


	public static  PLAYER_STATE MediaPlayState ;
	//1   播放状态   2 暂停状态


	private ACache aCache;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return mBinder;
	}


	public class LocalBinder extends Binder {
		public JCMusicPlayerService getService() {
			// Return this instance of LocalService so clients can call public methods
			return JCMusicPlayerService.this;
		}
	}

	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();

		aCache = ACache.get(getApplicationContext());

		mediaPlayer = new MediaPlayer();
		// 设定CUP锁定
		mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);


		mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

			@Override
			public void onPrepared(MediaPlayer mp) {
				// TODO Auto-generated method stub
				
				mp.start();

				Intent intent = new Intent(MusicMediaControllerFragment.CHANGE_NAME_IMG_AUTHOR);

				sendBroadcast(intent);

				if(timer==null){
					timer = new Timer();
				}

				timer.schedule(new TimerTask() {

					@Override
					public void run() {
						// TODO Auto-generated method stub

						updateUI();

					}

					
				}, 1000	, 1000);
			}
		});

		mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {

			@Override
			public void onBufferingUpdate(MediaPlayer mp, int percent) {
				// TODO Auto-generated method stub
				//	System.out.println("缓冲: %"+percent);
				bufferSize = percent;
			}
		});

		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

			@Override
			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				setNext();
			}
		});


		timer = new Timer();


		

		
		
		handler = new Handler(){
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
				case play:
					//当本地列表不为空的时候才可以播放  否则提示没有播放列表的 
					List<VoiceDetailBean> musicBeans2 = (List<VoiceDetailBean>) aCache.getAsObject(MUSIC_LIST_CATCHE);
					if(musicBeans2!=null){
						musicBeans = musicBeans2;
						mediaPlayer.start();
					}else{
						Toast.makeText(getApplicationContext(), "没有本地播放列表", 0).show();
					}

					break;
				case pause:
					mediaPlayer.pause();
					break;
				case next:
					cancleTimer();
					playNum = playNum+1;
					if(musicBeans!=null&&playNum>musicBeans.size()){
						playNum = musicBeans.size();  //已经是最后一个啦
					}
					System.out.println("播放xia 一个"+playNum);
					setResetMediaPlayer();
					break;
				case previous:

					cancleTimer();
					playNum = playNum-1;

					if(playNum<0){
						playNum =0;   //已经是第一个啦
					}

					System.out.println("播放上一个"+playNum);

					setResetMediaPlayer();
					break;
				case setList:
					
					setResetMediaPlayer();
					break;

				default:
					break;
				}
			};
		};

		broadcastReceiver = new BroadcastReceiver() {
			
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				
				if(intent.getAction().equals(MUSIC_PLAY)){
					handler.sendEmptyMessage(play);
				}
				if(intent.getAction().equals(MUSIC_PAUSE)){
					handler.sendEmptyMessage(pause);
				}
				if(intent.getAction().equals(MUSIC_NEXT)){
					handler.sendEmptyMessage(next);
				}
				if(intent.getAction().equals(MUSIC_PREVIOUS)){
					handler.sendEmptyMessage(previous);
				}
				if(intent.getAction().equals(MUSIC_SET_LIST)){
					List<VoiceDetailBean> mainInfoBeans = (List<VoiceDetailBean>) intent.getSerializableExtra(LIST_DATA);
					setMusicList(mainInfoBeans, intent.getIntExtra(LIST_POSTION, 0));
				}
				
			}
		};
		
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(MUSIC_NEXT);
		intentFilter.addAction(MUSIC_PAUSE);
		intentFilter.addAction(MUSIC_PLAY);
		intentFilter.addAction(MUSIC_PAUSE);
		intentFilter.addAction(MUSIC_SET_LIST);
		
		registerReceiver(broadcastReceiver, intentFilter);
	}
	
	
	private void updateUI() {
		// TODO Auto-generated method stub
		Intent intent = new Intent(MusicMediaControllerFragment.UPDATA_SEEKBAR_RECEIVER);
		intent.putExtra("musicSate", new MusicStateBean(mediaPlayer.getDuration(), bufferSize, mediaPlayer.getCurrentPosition()));
		sendBroadcast(intent);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(broadcastReceiver);
		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			            mediaPlayer.stop();
			             mediaPlayer.release();
			          mediaPlayer = null;
			       }
	}

	public void setResetMediaPlayer(){

		/**
		 * Preparing 状态：这个状态比较好理解，
		 * 主要是和prepareAsync()配合，如果异步准备完成，
		 * 会触发OnPreparedListener.onPrepared()，
		 * 进而进入Prepared状态。
		 */
		try {
			if(musicBeans!=null){
				mediaPlayer.reset();
				voiceDetailBean = musicBeans.get(playNum);
				if(musicBeans.get(playNum).getVideourl().trim().startsWith("file")){
					mediaPlayer.setDataSource(musicBeans.get(playNum).getVideourl());
					mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				}else{
					
					mediaPlayer.setDataSource(App.HTTP_PATH+musicBeans.get(playNum).getVideourl());
				}
				
				System.out.println("当前播放URL"+App.HTTP_PATH+musicBeans.get(playNum).getVideourl());
				//mediaPlayer.prepare();      //同步调用
				mediaPlayer.prepareAsync();   //异步调用
			}
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	public void setOnPreparedListener(OnPreparedListener onPreparedListener){
		this.onPreparedListener = onPreparedListener;
	}
	public void play(){

		handler.sendEmptyMessage(play);
	}

	public void seekTo(int seekSize){
		if(voiceDetailBean!=null){
			mediaPlayer.seekTo(seekSize);
		}else{
			updateUI();
		}
	}

	public void pause(){
		// cancleTimer();
		handler.sendEmptyMessage(pause);
	}
	/**
	 * 
	 * @返回当前音乐的总长度
	 */
	public int  getDuration(){  

		return mediaPlayer.getDuration();


	}

	/**
	 * 
	 * @返回当前音乐长度
	 */
	public int getCurrentPosition(){

		return mediaPlayer.getCurrentPosition();
	}

	/**
	 * 
	 * @return  当前播放器对象
	 */
	public MediaPlayer getMediaPlayer(){

		return mediaPlayer;
	}

	/**
	 * 播放上一个
	 */
	public void setPrevious(){
		handler.sendEmptyMessage(previous);
	}
	/**
	 * 播放xia 一个
	 */
	public void setNext(){
		handler.sendEmptyMessage(next);

	}




	/**
	 * 
	 * @param musicBeans  设置播放列表
	 */
	public void setMusicList(List<VoiceDetailBean> musicBeans,int playNum){
		this.musicBeans = musicBeans;
		this.playNum = playNum;
		aCache.put(MUSIC_LIST_CATCHE, (Serializable)musicBeans);
		handler.sendEmptyMessage(setList);

	}



	public void cancleTimer(){
		if(timer!=null){
			timer.cancel();
			timer = null;
		}
	}
}
